Beginners hands-on Guide to Golang
Hi, this is Charu from Classmethod. In this blog we will cover the basics, including setting up your Go environment, writing simple programs, understanding Go's type system, and exploring Go routines for concurrency.
Let's get started!
Setting Up Your Environment
The Go programming language can be installed from the official Go website. Follow the installation instructions for your operating system. Once installed, you can verify the installation by opening a terminal or command prompt and typing:
go version
This command should display the installed version of Go.
Your First Go Program
Let's start with the traditional "Hello, World!" program. Go programs are saved with a .go file extension. Create a file named hello.go and open it in your favorite text editor. Then, type the following code:
package main import "fmt" func main() { fmt.Println("Hello, World!") }
To run your program, open a terminal, navigate to the directory containing your hello.go file, and type:
go run hello.go
You should see "Hello, World!" printed to the terminal.
Explanation
package main: Every Go program starts with a package declaration. Packages are Go's way of organizing and reusing code. The main package is special because it defines a standalone executable program, not a library.
import "fmt": This line imports the fmt package, which contains functions for formatted I/O operations (similar to C's printf and scanf).
func main() { ... }: The main function is the entry point of your program. The curly braces {} enclose the function's body.
Understanding Go's Type System
Go is a statically typed language, which means that variables always have a specific type and that type cannot change. Basic types in Go include integers, floats, booleans, and strings. Here's an example that demonstrates variable declaration and a simple function:
package main import "fmt" func add(x int, y int) int { return x + y } func main() { var num1 int = 10 var num2 int = 20 sum := add(num1, num2) fmt.Println("Sum:", sum) }
Explanation
In this example, the add function takes two integer parameters and returns their sum, also an integer. The := syntax is shorthand for declaring and initializing a variable in one line, inferring the type automatically. If you have any confusion in understanding the difference between == and :=, you can refer this blog.
Concurrency with Goroutines
One of Go's most powerful features is its built-in support for concurrency via goroutines. A goroutine is a lightweight thread managed by the Go runtime. Here's how you can start a new goroutine:
package main import ( "fmt" "time" ) func say(s string) { for i := 0; i < 5; i++ { time.Sleep(250 * time.Millisecond) fmt.Println(s) } } func main() { go say("world") say("hello") }
Explanation
In this example, go say("world") starts a new goroutine. The program then calls say("hello") in the main goroutine. Since both calls to say are now asynchronous, they will execute concurrently. Hence, the output would look like this,
The program starts with the main function invoking two say functions – one directly and one as a new goroutine using the go keyword. The direct call prints "hello", and the goroutine prints "world".
The main function starts by launching the say("world") goroutine and then immediately calls say("hello") without waiting for the first call to finish.
Since the goroutine printing "world" is launched first, it schedules its first action to happen after 250ms. However, the main goroutine continues execution without delay and calls say("hello"), which also schedules its first print of "hello" after 250ms.
The main goroutine gets to execute next, printing "hello" twice before the "world" goroutine gets another chance to execute.
This process continues until both strings have been printed five times.
Next Steps
This blog has covered the very basics of Go to get you started. There's much more to explore, including:
As you become more comfortable with Go's syntax and features, you'll find it a powerful tool for a wide range of programming tasks, from simple scripts to complex web services. The official Go website offers extensive documentation and tutorials to help you on your journey.
Thank you for reading!
Happy Learning:)